package userCache;


import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.Hashtable;

public class UserCache {
	
	private static UserCache cache;
	
	private Hashtable<String, UserRef> userRefs;
	private ReferenceQueue<User> queue;
	
	private class UserRef extends SoftReference<User>{
		private String key = "";
		public UserRef(User referent, ReferenceQueue<User> q) {
			
			super(referent, q);
			key = referent.getId();
		}
		
	}
	
	private UserCache() {
		userRefs = new Hashtable<>();
		queue = new ReferenceQueue<>();
	}
	
	public static UserCache getInstance() {
		synchronized (UserCache.class) {
			if(cache == null) {
				synchronized (UserCache.class) {
					cache = new UserCache();
				}
			}
		}
		
		return cache;
	}
	private void cleanCache() {
		UserRef ref = null;
		while((ref=(UserRef) queue.poll())!= null) {
			userRefs.remove(ref.key);
		}
	}
	
	public void clearAll() {
		cleanCache();
		userRefs.clear();
		System.gc();
		System.runFinalization();
	}
	
	@SuppressWarnings("unused")
	private void cacheObject(User user) {
		cleanCache();
		UserRef ref = new UserRef(user, queue);
		userRefs.put(user.getId(), ref);
	}
	
	
	public User getObject(String id) {
		User user = null;
		if(userRefs.containsKey(id)) {
			
		}
		if(user == null) {
			
		}
		
		return user;
		
	}

}
